import "package:ct_pa_majordomo/config/roomIcons.dart";
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/apartment/associated_devices/index.dart";
import "package:ct_pa_majordomo/pages/apartment/check_in/index.dart";
import "package:ct_pa_majordomo/pages/apartment/check_out/index.dart";
import "package:ct_pa_majordomo/pages/apartment/room_detail/index.dart";
import "package:ct_pa_majordomo/pages/apartment/unlock_permission/index.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/index.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:ct_pa_majordomo/widgets/wrap_item.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

void roomOperation({
  required BuildContext context,
  required Map room,
  Map? info,
  Map? mainRenter,
  ValueChanged<bool>? onRefresh,
}) async {
    showModalBottomSheet(
        context: context,
        // isScrollControlled: true,
        builder: (BuildContext context) {
          bool _checkIn = info != null && info["checkInId"] != null;
          return Container(
            // height: 410,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: EdgeInsets.all(ThemeVars.paddingPage),
                  decoration: const BoxDecoration(
                    borderRadius: BorderRadius.only(topLeft: Radius.circular(15), topRight: Radius.circular(15)),
                    color: ThemeVars.colorBackground,
                  ),
                  child: Row(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("${room["buildingName"]} ${room["roomName"] ?? room["name"]}" ?? "", style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),),
                          Text("${room["groupName"]}", style: const TextStyle(fontSize: 12, color: ThemeVars.colorTextTer),)
                        ],
                      )
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(ThemeVars.paddingPage),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (mainRenter != null) Container(
                        padding: const EdgeInsets.all(ThemeVars.paddingPage),
                        decoration: const BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(8)),
                            color: ThemeVars.colorBackground
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(mainRenter["name"]),
                                Text("${info?["checkInStart"]} - ${info?["checkInEnd"]}", style: const TextStyle(fontSize: 13, color: ThemeVars.colorTextSec),),
                              ],
                            ),
                            DefaultTextStyle(
                                style: const TextStyle(color: ThemeVars.colorPrimary, fontSize: 14),
                                child: GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Stacker.pop();
                                    Stacker.pushNamed(Keys.CHECK_IN_DETAIL, arguments: {
                                      "checkInId": mainRenter["checkInId"],
                                      "changeInfo": () {
                                        if (onRefresh != null) onRefresh(true);
                                      }
                                    });
                                  },
                                  child: const Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: [
                                      Text("详情"),
                                      Icon(Icons.arrow_forward_ios, size: 14, color: ThemeVars.colorPrimary,)
                                    ],
                                  ),
                                )
                            )
                          ],
                        ),
                      ),
                      const SizedBox(height: 12,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          if (!_checkIn) Expanded(
                            child: Button(
                                type: ButtonType.primaryOutline,
                                onPressed: () {
                                  Navigator.of(context).pop();
                                  Stacker.pushNamed(Keys.APARTMENT_CHECK_IN, arguments: room)
                                    .then((refresh) {
                                      print("办理入住：》》》 $refresh");
                                      if (refresh != null && refresh as bool) {
                                        print("办理入住onRefresh：》》》 ${onRefresh != null}");
                                        if (onRefresh != null) onRefresh(true);
                                      }
                                    });
                                },
                                child: const Text("办理入住", style: TextStyle(fontSize: 14),)
                            ),
                          ),
                          if (_checkIn) ...[
                            Expanded(
                              child: Button(
                                type: ButtonType.primaryOutline,
                                onPressed: () {
                                  Navigator.pop(context);
                                  taiDialog(
                                    context: context,
                                    child: const Text("确定办理退房？", textAlign: TextAlign.center,),
                                    onConfirm: (taiContext) async {
                                      await apartmentApi.checkOut(info["checkInId"]);
                                      EasyLoading.showSuccess("退房成功");
                                      if (onRefresh != null) onRefresh(true);
                                      Navigator.of(taiContext).pop();
                                    }
                                  );
                                },
                                child: const Text("退房", style: TextStyle(fontSize: 14),)
                              ),
                            ),
                            SizedBox(width: 10,),
                            Expanded(
                              child: Button(
                                type: ButtonType.primaryOutline,
                                onPressed: () {
                                  Navigator.pop(context);
                                  showDatetimePicker(
                                    context: context,
                                    initialDateTime: DateTime.parse(info["checkInEnd"]).add(const Duration(days: 1)),
                                    minimumDate: DateTime.parse(info["checkInEnd"]).add(const Duration(days: 1)),
                                    onchange: (value) async {
                                      print("时间是：》》》$value");
                                      Map<String, dynamic> params = {
                                        "checkInId": info["checkInId"],
                                        "checkInEnd": DateTools.formatTime(value.millisecondsSinceEpoch, format: "{y}-{m}-{d}"),
                                      };
                                      await apartmentApi.updateCheckIn(params);
                                      EasyLoading.showSuccess("续租成功");
                                      if (onRefresh != null) onRefresh(true);
                                    }
                                  );
                                },
                                child: const Text("续租", style: TextStyle(fontSize: 14),)
                              ),
                            )
                          ],
                        ],
                      ),
                      SizedBox(height: 12,),
                      Wrap(
                        children: [
                          if (_checkIn) WrapItem(
                              span: 4,
                              child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.pop(context);
                                  Stacker.pushNamed(Keys.APARTMENT_UNLOCK_PERMISSION, arguments: info);
                                },
                                child: Container(
                                  padding: const EdgeInsets.symmetric(vertical: 12),
                                  child: Center(
                                    child: Column(
                                      children: [
                                        Container(
                                          width: 50,
                                          height: 50,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(40),
                                            color: ThemeVars.colorPrimaryLight,
                                          ),
                                          child: Icon(RoomIcons.unlock_permission, size: 30,),
                                        ),
                                        SizedBox(height: 4,),
                                        Text("开门权限"),
                                      ],
                                    ),
                                  ),
                                ),
                              )
                          ),
                          WrapItem(
                              span: 4,
                              child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.pop(context);
                                  Stacker.pushNamed(Keys.APARTMENT_ROOM_DETAIL, arguments: {"info": info, "room": {...room, "roomName": room["name"] ?? room["roomName"]}});
                                },
                                child: Container(
                                  padding: const EdgeInsets.symmetric(vertical: 12),
                                  child: Center(
                                    child: Column(
                                      children: [
                                        Container(
                                          width: 50,
                                          height: 50,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(40),
                                            color: ThemeVars.colorPrimaryLight,
                                          ),
                                          child: Icon(RoomIcons.room_detail, size: 30,),
                                        ),
                                        SizedBox(height: 4,),
                                        Text("房间详情"),
                                      ],
                                    ),
                                  ),
                                ),
                              )
                          ),
                          if (room["associatedMeterList"].isNotEmpty) WrapItem(
                              span: 4,
                              child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.pop(context);
                                  Stacker.pushNamed(Keys.APARTMENT_UTILITIES_RECHARGE, arguments: {
                                    "roomId": room["roomId"],
                                    "roomName": room["roomName"] ?? room["name"],
                                    "buildingName": room["buildingName"]
                                  });
                                },
                                child: Container(
                                  padding: const EdgeInsets.symmetric(vertical: 12),
                                  child: Center(
                                    child: Column(
                                      children: [
                                        Container(
                                          width: 50,
                                          height: 50,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(40),
                                            color: ThemeVars.colorPrimaryLight,
                                          ),
                                          child: Icon(RoomIcons.resources_recharge, size: 30,),
                                        ),
                                        SizedBox(height: 4,),
                                        Text("水电充值"),
                                      ],
                                    ),
                                  ),
                                ),
                              )
                          ),
                          WrapItem(
                              span: 4,
                              child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.pop(context);
                                  Stacker.pushNamed(Keys.APARTMENT_ASSOCIATED_DEVICES, arguments: {"roomId": room["roomId"], "roomName": room["roomName"] ?? room["name"], "buildingName": room["buildingName"]});
                                },
                                child: Container(
                                  padding: const EdgeInsets.symmetric(vertical: 12),
                                  child: Center(
                                    child: Column(
                                      children: [
                                        Container(
                                          width: 50,
                                          height: 50,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(40),
                                            color: ThemeVars.colorPrimaryLight,
                                          ),
                                          child: Icon(RoomIcons.associated_device, size: 30,),
                                        ),
                                        SizedBox(height: 4,),
                                        Text("关联设备"),
                                      ],
                                    ),
                                  ),
                                ),
                              )
                          ),
                          WrapItem(
                              span: 4,
                              child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () async {
                                  try {
                                    if (room["roomDirtyStatus"] == "1") {
                                      await apartmentApi.cleanRoom(room["roomId"]);
                                      EasyLoading.showSuccess("已设置为净房");
                                    } else {
                                      await apartmentApi.dirtyRoom(room["roomId"]);
                                      EasyLoading.showSuccess("已设置为脏房");
                                    }
                                    Navigator.pop(context);
                                    if (onRefresh != null) onRefresh(true);
                                  } catch (e) {
                                    EasyLoading.showError(e.toString());
                                  }
                                },
                                child: Container(
                                  padding: const EdgeInsets.symmetric(vertical: 12),
                                  child: Center(
                                    child: Column(
                                      children: [
                                        Container(
                                          width: 50,
                                          height: 50,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(40),
                                            color: ThemeVars.colorPrimaryLight,
                                          ),
                                          child: Icon(
                                            room["roomDirtyStatus"] == "1" 
                                              ? RoomIcons.clean_room
                                              : RoomIcons.clean_room,
                                            size: 30,
                                            color: room["roomDirtyStatus"] == "1"
                                              ? ThemeVars.colorPrimary
                                              : null,
                                          ),
                                        ),
                                        SizedBox(height: 4,),
                                        Text(room["roomDirtyStatus"] == "1" ? "置为净房" : "设为脏房"),
                                      ],
                                    ),
                                  ),
                                ),
                              )
                          ),
                        ],
                      ),
                    ],
                  ),
                )
              ],
            ),
          );
        }
    );
}
